package cn.usian.basicInformation.sensitivewords.config;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 敏感词工具类
 */
public class TrieUtils {


    //通过map保存子树
    private Map<Character, TrieUtils> children;
    private boolean isEnd;

    public TrieUtils() {
        children = new HashMap<>();
        isEnd = false;
    }

    //将敏感词插入到前缀树中
    public void insert(String word) {
        TrieUtils node = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            TrieUtils childrenNode = node.children.get(ch);
            if (childrenNode == null) {
                node.children.put(ch, new TrieUtils());
            }
            node = node.children.get(ch);
        }
        node.isEnd = true;
    }

    // 检测文本中是否包含敏感词，并返回第一个匹配到的敏感词
    public String detectSensitiveWord(String word, int start) {
        TrieUtils node = this;
        StringBuilder detectedWord = new StringBuilder();

        for (int i = start; i < word.length(); i++) {
            char ch = word.charAt(i);
            TrieUtils childrenNode = node.children.get(ch);

            if (childrenNode == null) {
                // 说明后面没有匹配的了
                break;
            } else {
                detectedWord.append(ch);
                node = childrenNode;
                if (node.isEnd) {
                    return detectedWord.toString(); // 返回检测到的敏感词
                }
            }
        }

        return null; // 没有匹配到敏感词
    }

    //检查一个单词是否存在敏感词
    public String sensitiveWord(String word) {
        //不断向前移动检查
        for (int i = 0; i < word.length(); i++) {
            if (!Objects.isNull(detectSensitiveWord(word, i))) {
                return detectSensitiveWord(word, i);
            }
        }
        return null;
    }



}